//
//  OauthViewController.swift
//  SinaWeibo
//
//  Created by apple on 15/11/10.
//  Copyright © 2015年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD

import AFNetworking
/*
App Key：1831572088
App Secret：14bdd2aab9424167dce6ec5d1b846a13
*/

class OauthViewController: UIViewController {
    
    //手码创建webView
    
   
    
    let webView = UIWebView()
    
    override func loadView() {
        
        view = webView
    }
    
    //实现按钮的监听方法
    
    @objc func close () {
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc func fullAccount() {
        
        let jsString = "document.getElementById('userId').value = '15247191827' , document.getElementById('passwd').value = '910802bboygang';"
        webView.stringByEvaluatingJavaScriptFromString(jsString)
        
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setUpUI()
        
        webView.delegate = self
        
        //跳转到新浪微博授权登陆网页
        loadOauthPage()
        
    }
    override func viewWillDisappear(animated: Bool) {
        
        super.viewWillDisappear(animated)
        SVProgressHUD.dismiss()
    }
   
    //加载网页登陆页面
    func loadOauthPage() {
        
        let urlString = "https://api.weibo.com/oauth2/authorize?" + "client_id=" +  client_id + "&redirect_uri=" + redirect_uri
        
        let url = NSURL(string: urlString)
        
        let request = NSURLRequest(URL: url!)
        
        webView.loadRequest(request)
        
        
    }
    func setUpUI () {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: .Plain, target: self, action: "close")
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style: .Plain, target: self, action: "fullAccount")
    }
}
extension OauthViewController:UIWebViewDelegate {
    
    //开始加载网页的时候显示
    func webViewDidStartLoad(webView: UIWebView) {
        
        SVProgressHUD.show()
    }
    
    //加载完毕以后消失
    func webViewDidFinishLoad(webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        
        guard let urlSrtring = request.URL?.absoluteString else {
            
            return false
        }
        
        if urlSrtring.hasPrefix("https://api.weibo.com") {
            
            return true
        }
        
        if !urlSrtring.hasPrefix(redirect_uri) {
            
            return false
        }
        
        //程序走到这里 就说明 一定包含了 回调的url
        guard let query = request.URL?.query else {
            
            return false
        }
        
        let codeStr = "code="
        
        let code = query.substringFromIndex(codeStr.endIndex)
        
        print(code)
        
        UserAccountViewModel().loadAccessToken(code) { (error) -> () in
            
            if error != nil {
                
                SVProgressHUD.showErrorWithStatus("网络正在抽风 请稍后")
                return
            }
            
            
            self.dismissViewControllerAnimated(false, completion: { () -> Void in
                
                //发送通知
                NSNotificationCenter.defaultCenter().postNotificationName(appSwitchToViewController, object: "welcome")
            })
        }
        
        return false
        
    }
    
    
}
